import { getStarList, updateAdvisorStarService } from '@/api'
import { NonRealtimeService, RealtimeService } from '@/store/constant'
import { StarServiceItem } from '@/types/common'
import { ServiceStatusEnum } from '@/types/enum'
import { SET_SNACKBAR } from '@/store/actions'

const useWorkStatus = () => {
  const dispatch = useDispatch()
  const { runAsync: getStar, error: fetchError } = useRequest(getStarList, {
    manual: true,
    debounceWait: 500,
    onBefore() {
      setRecord({ ...record, loading: true })
    },
    onError: () => {
      setRecord({ ...record, loading: false })
    }
  })

  const { runAsync: updateService, error: updateError } = useRequest(updateAdvisorStarService, {
    manual: true,
    debounceWait: 500,
    onFinally: (_params, data, error) => {
      console.log(data, error)
      setRecord({ ...record, loading: false })
      dispatch({
        type: SET_SNACKBAR,
        payload: { children: `操作${error ? '失败: ' + error.message : '成功'}`, severity: error ? 'error' : 'success' }
      })
    }
  })

  const params = { page: 1, size: 20 }
  const [record, setRecord] = useState({
    loading: false
  })
  // 关闭实时或者非实时
  const offlineService = async ({ starId, type }: { starId: string; type: 'realtime' | 'nonRealtime' }) => {
    const res = await getStar({ ...params, star_id: starId })
    const star = res?.data?.[0]
    if (star) {
      const { services } = star
      const serviceList = type == 'realtime' ? RealtimeService : NonRealtimeService
      const newServices = map(services, (service: StarServiceItem) => {
        if (serviceList.includes(service.type)) {
          return { ...service, status: ServiceStatusEnum.Shutdown }
        }
        return service
      })
      const res = await updateService({ star_id: starId, services: newServices })
      return res
    }
  }
  return { ...record, error: fetchError || updateError, offlineService }
}
export default useWorkStatus
